﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuThuTien : Form
    {
        #region Khai bao toan cuc
        public event FormClosePhieuNhapKhoEventHandler fromClosePhieuThuTien = null;
        private PhieuThuTienManagement phieuthutienMgt = new PhieuThuTienManagement();
        private ChiNhanhCongTyMgt chinhanhcongtyMgt = new ChiNhanhCongTyMgt();
        private KhachHangManagement khachhangMgt = new KhachHangManagement();
        private NhanVienMgt nhanvienMgt = new NhanVienMgt();
        private NhaCungCapManagement nhacungcapMgt = new NhaCungCapManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private PhieuThuTien phieuthutien = null;
        private PhieuXuatHang phieuxuathang = new PhieuXuatHang();
        bool IsEdited = false;
        private int idLoaiPhieu = 11;

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private NhanVien nhanvien;
        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        #endregion

        #region Xu ly form load
        public FrmPhieuThuTien()
        {
            InitializeComponent();            
        }

        public FrmPhieuThuTien(PhieuThuTien phieuthutien, NhanVien nv)
        {
            InitializeComponent();
            this.phieuthutien = phieuthutien;
            this.nhanvien = nv;

            BindingToCbo();

            dtOld = this.phieuthutien.NgayThang;
            dtpNgayThuTien.Value = this.phieuthutien.NgayThang;

            prefixOld = this.phieuthutien.Prefix;
            cboPrefix.Text = this.phieuthutien.Prefix;
            txtMaPhieuThu.Text = this.phieuthutien.OrderNumber;

            cboDonViThu.SelectedValue = this.phieuthutien.IdChiNhanhCongTy;
            txtNguoiLap.Text = this.phieuthutien.NguoiLap;
            txtNguoiNopTien.Text = this.phieuthutien.NguoiNopTien;
            txtLyDo.Text = this.phieuthutien.LyDo;
            txtSoTien.Text = this.phieuthutien.SoTien.ToString();
            lblIDPhieuXuat.Text = this.phieuxuathang.Id.ToString();
            txtKemTheo.Text = this.phieuthutien.ChungTuKemTheo;
            cboDoiTuong.Text = this.phieuthutien.DoiTuong;
            cboLoaiDoiTuong.SelectedIndex = 0;
            lblID.Text = this.phieuthutien.Id.ToString();

            groupBox1.Enabled = false;
            lblIDPhieuXuat.Visible = false;
            lblID.Visible = false;
            btnThem.Enabled = true;
            btnSua.Enabled = true;
            btnXoa.Enabled = true;
            btnLuu.Enabled = false;
            btnDinhKhoan.Enabled = true;
            btnIn.Enabled = true;
        }

        public FrmPhieuThuTien(PhieuXuatHang phieuxuathang, long sotien, long st, NhanVien nv)
        {
            InitializeComponent();

            this.nhanvien = nv;
            this.phieuxuathang = phieuxuathang;

            BindingToCbo();

            cboDonViThu.SelectedValue = phieuxuathang.IdChiNhanhCongTy;
            txtNguoiLap.Text = nhanvien.HoTen;
            txtSoTien.Text = sotien.ToString();
            txtSoTienDaTra.Text = st.ToString();
            lblIDPhieuXuat.Text = phieuxuathang.Id.ToString();
            txtKemTheo.Text = phieuxuathang.MaSo.ToString();
            cboLoaiDoiTuong.SelectedIndex = 0;
            cboDoiTuong.Text = phieuxuathang.KhachHang.ToString();

            ChangeStatusControl(false, groupBox1);
            lblIDPhieuXuat.Visible = false;
            lblID.Visible = false;
            btnThem.Enabled = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
        }

        public FrmPhieuThuTien(NhanVien nv)
        {
            InitializeComponent();

            groupBox1.Enabled = true;
            this.nhanvien = nv;
            txtNguoiLap.Text = nhanvien.HoTen; 
            cboLoaiDoiTuong.SelectedIndex = 0;

            BindingToCbo();

            lblIDPhieuXuat.Text = "0";
            lblIDPhieuXuat.Visible = false;
            lblID.Visible = false;
            txtKemTheo.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        public void ChangeStatusControl(bool IsReadOnly, Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c is TextBox)
                {
                    if (IsReadOnly)
                    {
                        ((TextBox)c).ReadOnly = true;
                    }
                    else
                    {
                        ((TextBox)c).ReadOnly = false;
                    }
                }
                else if (c is DateTimePicker)
                {
                    if (IsReadOnly)
                    {
                        ((DateTimePicker)c).Enabled = false;
                    }
                    else
                    {
                        ((DateTimePicker)c).Enabled = true;
                    }
                }
            }
        }

        public void ChangeStatusTextBox(bool IsReadOnly)
        {
            if (IsReadOnly)
            {
                txtLyDo.ReadOnly = true;
                txtKemTheo.ReadOnly = true;
                txtNguoiLap.ReadOnly = true;
                txtLyDo.ReadOnly = true;
                txtSoTien.ReadOnly = true;
                txtNguoiNopTien.ReadOnly = true;
                dtpNgayThuTien.Enabled = false;
            }
            else
            {
                txtLyDo.ReadOnly = false;
                txtKemTheo.ReadOnly = false;
                txtNguoiLap.ReadOnly = false;
                txtLyDo.ReadOnly = false;
                txtSoTien.ReadOnly = false;
                txtNguoiNopTien.ReadOnly = false;
                dtpNgayThuTien.Enabled = true;
            }
        }

        #endregion

        #region Xu ly cac button

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            btnLuu.Enabled = true;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;
            groupBox1.Enabled = true;

            prefixOld = "";
            dtOld = new DateTime();

            RefreshControl();
            ChangeStatusTextBox(false);
            txtMaPhieuThu.ReadOnly = true;
            btnDinhKhoan.Enabled = false;
            dtpNgayThuTien.Select();            
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (this.phieuthutien != null)
            {
                List<PhieuThuTien> lstPhieuTHuTien = (from ptt in GetAllPhieuThuTien()
                                                      where ptt.MaSo == this.phieuthutien.MaSo
                                                      select ptt).ToList();
                ResultObj resultObj = new ResultObj();
                if (lstPhieuTHuTien.Count > 0)
                {
                    lstPhieuTHuTien[0].IsDelete = 1;
                    resultObj = phieuthutienMgt.UpdatePhieuThuTien(lstPhieuTHuTien[0]);
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Đã xoá thành công", "Thông báo");
                    EditOrRemoveDinhKhoan(lstPhieuTHuTien[0].MaSo);
                    this.Close();
                    if (this.fromClosePhieuThuTien != null)
                        this.fromClosePhieuThuTien();
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (txtMaPhieuThu.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mã phiếu");
                return;
            }

            if (txtSoTien.Text == "")
            {
                MessageBox.Show("Bạn chưa nhập đầy đủ dữ liệu");
                return;
            }

            ResultObj result = new ResultObj();

            string sNguoiLap = txtNguoiLap.Text;
            string sPrefix = cboPrefix.Text;
            string sOrderNumber = txtMaPhieuThu.Text;
            string sMaSo = sPrefix + "/" + dtpNgayThuTien.Value.ToString("MM") + dtpNgayThuTien.Value.ToString("yy") + "/" + sOrderNumber;
            string sLyDo = txtLyDo.Text;
            string sNguoiNopTien = txtNguoiNopTien.Text;
            string sChungTu = txtKemTheo.Text;

            DateTime sngaythang = dtpNgayThuTien.Value;
            int IdPhieuXuat = Convert.ToInt32(lblIDPhieuXuat.Text);
            phieuthutien = new PhieuThuTien();

            phieuthutien.IdChiNhanhCongTy = ((ChiNhanhCongTy)cboDonViThu.SelectedItem).Id;
            phieuthutien.Prefix = sPrefix;
            phieuthutien.OrderNumber = sOrderNumber;
            phieuthutien.MaSo = sMaSo;
            phieuthutien.History = "";
            phieuthutien.NguoiLap = sNguoiLap;
            phieuthutien.NguoiNopTien = sNguoiNopTien;            
            phieuthutien.ChungTuKemTheo = txtKemTheo.Text;
            phieuthutien.LyDo = txtLyDo.Text;
            phieuthutien.NgayThang = sngaythang;
            phieuthutien.DoiTuong = cboDoiTuong.Text;
            phieuthutien.IdPhieuXuatHang = IdPhieuXuat;
            phieuthutien.IsDelete = 0;
            phieuthutien.SoTien = Convert.ToInt64(txtSoTien.Text.Replace(".", ""));

            if (!IsEdited)
            {
                result = phieuthutienMgt.SaveNewPhieuThuTien(phieuthutien);
                lblID.Text = result.ReturnCode.ToString();
            }
            else
            {
                phieuthutien.Id= Convert.ToInt32(lblID.Text);
                result = phieuthutienMgt.UpdatePhieuThuTien(phieuthutien);                
                IsEdited = false;
            }
            if (result.ReturnCode > 0)
            {
                EditOrRemoveDinhKhoan(phieuthutien.MaSo);
                MessageBox.Show("Lưu thành công. Vui lòng cập nhật lại các bút toán.", "Thông báo");

                groupBox1.Enabled = false;
                btnLuu.Enabled = false;
                btnDinhKhoan.Enabled = true;
                btnSua.Enabled = true;
                btnXoa.Enabled = true;
                btnThem.Enabled = true;
                btnIn.Enabled = true;
            }
            else if (result.ReturnCode == Definitions.DUPLICATED_VALUE)
                MessageBox.Show("Dữ liệu bị trùng","Thông báo");
            else
                MessageBox.Show("Thất bại");
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (this.phieuthutien != null)
            {
                txtMaPhieuThu.Enabled = false;
                groupBox1.Enabled = true;

                IsEdited = true;
                btnThem.Enabled = false;
                btnXoa.Enabled = false;
                btnLuu.Enabled = true;
                btnDinhKhoan.Enabled = false;
                btnIn.Enabled = false;
                btnSua.Enabled = false;
            }
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            long tien = 0;
            tien = Convert.ToInt64(txtSoTien.Text.Replace(".", ""));

            FrmDinhKhoanPhieuThuTien frmDinhKhoan = new FrmDinhKhoanPhieuThuTien(tien);
            frmDinhKhoan.PhieuThuTien = this.phieuthutien;
            frmDinhKhoan.ShowDialog();
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            string sLoaiPhieuThu = "";
            if (phieuxuathang != null)
                sLoaiPhieuThu = "tiền hàng";

            string tienchu = CNum2Char.So2Chu((long)Convert.ToDouble(txtSoTien.Text.Replace(".", "")));
            string diachi = lblDiaChi.Text;

            FrmXemReport frm = new FrmXemReport(phieuthutien, sLoaiPhieuThu, tienchu, diachi);
            this.Hide();
            frm.ShowDialog();
            this.Show();
        }

        #endregion

        #region Xu ly cac su kien

        public void RefreshControl()
        {
            txtNguoiNopTien.Text = "";
            txtLyDo.Text = "";
            txtKemTheo.Text = "";
            txtSoTien.Text = "";
            txtSoTienDaTra.Text = "";
            cboPrefix.Text = "";

            cboDonViThu.SelectedIndex = -1;
            cboLoaiDoiTuong.SelectedIndex = -1;
            cboDoiTuong.SelectedIndex = -1;

            lblID.Text = "";
            dtpNgayThuTien.Value = DateTime.Now;
        }

        private void BindingToCbo()
        {
            cboDonViThu.DataSource = GetAllChiNhanhCongTy();
            cboDonViThu.DisplayMember = "TenChiNhanh";
            cboDonViThu.ValueMember = "Id";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";
        }

        private void dtpNgayThuTien_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgayThuTien.Value)
                txtMaPhieuThu.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayThuTien.Value);
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaPhieuThu.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayThuTien.Value);
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        private void cboLoaiDoiTuong_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboLoaiDoiTuong.SelectedIndex > -1)
            {
                int loaidoituong = cboLoaiDoiTuong.SelectedIndex;
                switch (loaidoituong)
                {
                    case 0:
                        {
                            cboDoiTuong.DataSource = GetAllKhachHang();
                            cboDoiTuong.DisplayMember = "Ten";
                            cboDoiTuong.ValueMember = "Id";
                        }
                        break;
                    case 1:
                        {
                            cboDoiTuong.DataSource = GetAllNhaCungCap();
                            cboDoiTuong.DisplayMember = "TenNhaCungCap";
                            cboDoiTuong.ValueMember = "Id";
                        }
                        break;
                    case 2:
                        {
                            cboDoiTuong.DataSource = GetAllNhanVien();
                            cboDoiTuong.DisplayMember = "HoTen";
                            cboDoiTuong.ValueMember = "Id";
                        }
                        break;
                }
            }
        }

        private void cboDoiTuong_SelectedValueChanged(object sender, EventArgs e)
        {
            int loaidoituong = cboLoaiDoiTuong.SelectedIndex;
            if (cboDoiTuong.SelectedItem != null)
            {
                switch (loaidoituong)
                {
                    case 0:
                        lblDiaChi.Text = ((KhachHang)cboDoiTuong.SelectedItem).DiaChi;
                        break;
                    case 1:
                        lblDiaChi.Text = ((NhaCungCap)cboDoiTuong.SelectedItem).DiaChi;
                        break;
                    case 2:
                        lblDiaChi.Text = "";
                        break;
                }
            }
        }

        private void txtSoTien_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != ',' && e.KeyChar != '.' && e.KeyChar != (char)46 && e.KeyChar != (char)8)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
                {
                    e.Handled = true;
                    MessageBox.Show("Số tiền bạn chỉ được nhập số ");
                }
            }
        }

        private void cboVAT_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != ',' && e.KeyChar != '.' && e.KeyChar != (char)46 && e.KeyChar != (char)8)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
                {
                    e.Handled = true;
                    MessageBox.Show("VAT bạn chỉ được nhập số ");
                }
            }
        }

        private void cboDonViThu_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboDonViThu.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboDonViThu.Text) && cboDonViThu.Text != "")
                {
                    cboDonViThu.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboDonViThu.SelectedValue == null)
            {
                cboDonViThu.Text = "";
            }
        }

        private void cboDoiTuong_Leave(object sender, EventArgs e)
        {
            if (cboLoaiDoiTuong.SelectedIndex == 0)
            {
                foreach (KhachHang c in cboDoiTuong.Items)
                {
                    if (c.Ten.ToLower().Contains(cboDoiTuong.Text) && cboDoiTuong.Text != "")
                    {
                        cboDoiTuong.SelectedValue = c.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 1)
            {
                foreach (NhaCungCap p in cboDoiTuong.Items)
                {
                    if (p.TenNhaCungCap.ToLower().Contains(cboDoiTuong.Text))
                    {
                        cboDoiTuong.SelectedValue = p.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 2)
            {
                foreach (NhanVien emp in cboDoiTuong.Items)
                {
                    if (emp.HoTen.ToLower().Contains(cboDoiTuong.Text))
                    {
                        cboDoiTuong.SelectedValue = emp.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 3)
            {
                foreach (ChiNhanhCongTy b in cboDoiTuong.Items)
                {
                    if (b.TenChiNhanh.ToLower().Contains(cboDoiTuong.Text))
                    {
                        cboDoiTuong.SelectedValue = b.Id;
                        break;
                    }
                }
            }

            if (cboDoiTuong.SelectedValue == null)
            {
                cboDoiTuong.Text = "";
            }
        }

        private void txtSoTienDaTra_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != ',' && e.KeyChar != '.' && e.KeyChar != (char)46 && e.KeyChar != (char)8)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
                {
                    e.Handled = true;
                    MessageBox.Show("Số tiền đã trả chỉ được nhập số ");
                }
            }
        }

        private void txtSoTien_TextChanged(object sender, EventArgs e)
        {
            if (txtSoTien.Text != "")
            {
                txtSoTien.SelectionStart = txtSoTien.Text.Length + 1;
                string num = txtSoTien.Text.Replace(".", "");
                txtSoTien.Text = (Convert.ToInt64(num).ToString("N0")).Replace(",", ".");
            }
        }

        private void txtMaPhieuThu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtMaPhieuThu_Leave(object sender, EventArgs e)
        {
            bool isDup = KiemTraMaSo.CheckOrderNumber(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, txtMaPhieuThu.Text, idLoaiPhieu, dtpNgayThuTien.Value);
            if (isDup)
            {
                MessageBox.Show("Mã phiếu bị trùng");
                txtMaPhieuThu.Focus();
            }
        }

        #endregion

        #region Lay cac du lieu

        public List<PhieuThuTien> GetAllPhieuThuTien()
        {
            ResultObj result = new ResultObj();
            result = phieuthutienMgt.GetAllPhieuThuTien();
            List<PhieuThuTien> lstPhieuThuTien = (List<PhieuThuTien>)result.Result;
            return lstPhieuThuTien;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj result = new ResultObj();
            result = chinhanhcongtyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> lstChiNhanhCongTy = (List<ChiNhanhCongTy>)result.Result;
            return lstChiNhanhCongTy;
        }

        public List<KhachHang> GetAllKhachHang()
        {
            ResultObj result = new ResultObj();
            result = khachhangMgt.GetAllKhachHang();
            List<KhachHang> lstKhachHang = (List<KhachHang>)result.Result;
            return lstKhachHang;
        }

        public List<NhaCungCap> GetAllNhaCungCap()
        {
            ResultObj result = new ResultObj();
            result = nhacungcapMgt.GetAllNhaCungCap();
            List<NhaCungCap> lstNhaCungCap = (List<NhaCungCap>)result.Result;
            return lstNhaCungCap;
        }

        public List<NhanVien> GetAllNhanVien()
        {
            ResultObj result = new ResultObj();
            result = nhanvienMgt.GetAllNhanVien();
            List<NhanVien> lstNhanVien = (List<NhanVien>)result.Result;
            return lstNhanVien;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }
        #endregion
    }
}
